package com.ruoyi.system.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import com.ruoyi.common.utils.StringUtils;

/**
 * 二维码生成器
 */
public class BarcodeGeneratorUtil {

    public static String generateBarcode(String filePath,String barcode) throws Exception {

        if(StringUtils.isEmpty(barcode)){
            barcode = getRandomNum();
        }

        String fileName = barcode + "_barcode.png";

        // 创建编码提示信息，例如字符编码等
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码为UTF-8

        // 生成条形码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(barcode, BarcodeFormat.QR_CODE, 300, 100, hints);

        // 将BitMatrix转换为图像并写入文件系统
        Path path = FileSystems.getDefault().getPath(filePath+fileName);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        return fileName;
    }

    public static String getRandomNum(){
        return 100000000 + (int)(Math.random() * 900000000)+"";
    }
}
